import React, { useEffect, useRef } from 'react';
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';

export default function index() {
  const mountRef = useRef(null);

  useEffect(() => {
    const scene = new THREE.Scene();

    const camera = new THREE.PerspectiveCamera(75);
    camera.position.z = 15;
    camera.position.x = 1;
    camera.position.y = 1;
    scene.add(camera);

    // 缓冲几何体
    // 1、顶点坐标数组
    const count = 500; // 三角形数量
    const positionArray = new Float32Array(count * 3 * 3); // 数组长度=三角形数量*每个三角形三个点*每个点三个坐标值
    for (let i = 0; i < count * 3 * 3; i++) {
      positionArray[i] = (Math.random() - 0.5) * 4;
    }

    // 2、生成缓冲属性
    const positionAttribute = new THREE.BufferAttribute(positionArray, 3); // THREE.BufferAttribute(顶点数组, 每个点坐标值)

    // 3、创建缓冲几何体
    const bufferGeom = new THREE.BufferGeometry();

    // 4、设置缓冲几何体的属性
    bufferGeom.setAttribute('position', positionAttribute);

    const meterial = new THREE.MeshBasicMaterial({
      color: 0xff0000,
      wireframe: true,
    });

    const mesh = new THREE.Mesh(bufferGeom, meterial);
    scene.add(mesh);

    const renderer = new THREE.WebGLRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight);
    mountRef.current.appendChild(renderer.domElement);
    renderer.render(scene, camera);

    const controls = new OrbitControls(camera, renderer.domElement);

    const animate = () => {
      controls.update();
      renderer.render(scene, camera);
      window.requestAnimationFrame(animate);
    };
    animate();
  }, []);

  return (
    <div
      ref={mountRef}
      style={{ width: '100%', height: '100vh' }}
    />
  );
}
